package com.jybd.live.controller;

import com.aliyuncs.utils.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jybd.live.model.Record;
import com.jybd.live.service.AliLiveService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@RestController
@RequestMapping("aliCallBack")
/**
 * 阿里云回调接口
 */
public class ALiCallBackController {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    private AliLiveService  aliLiveService;

    @Autowired
    public ALiCallBackController(AliLiveService aliLiveService) {
        this.aliLiveService = aliLiveService;
    }

    /**
     * 录制回调
     * @param request
     * @return
     */
    @RequestMapping("rec")
    public String RECCallBack(HttpServletRequest request){
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(request.getInputStream(),"utf-8");
            BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
            StringBuffer requestBodyBuffer = new StringBuffer();
            String str=null;
            while((str=bufferedReader.readLine())!=null){
                requestBodyBuffer.append(str);
            }
            String requestBodyStr = requestBodyBuffer.toString();
            if(!StringUtils.isEmpty(requestBodyStr)){
                Record record = new ObjectMapper().readValue(requestBodyStr, Record.class);
                if(!aliLiveService.insertRecord(record)){
                    log.error("insert record fail : " + requestBodyStr);
                }
            }
            requestBodyBuffer.insert(0,"ALiCallBackController.rec receive callBack message: ");
            log.info(requestBodyBuffer.toString());
            inputStreamReader.close();
            bufferedReader.close();
        }  catch (IOException e) {
            log.error(e.getMessage());
        }
        return "ok";
    }

}
